package com.xmy.cultivate.service;

import com.xmy.cultivate.bean.AccessTokenBean;
import com.xmy.cultivate.config.WeCharConfig;
import com.xmy.cultivate.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import com.alibaba.fastjson.JSONObject;

@Service
public class AccessTokenService {
    @Autowired
    private WeCharConfig charConfig;
    /**
     * access token 对象
     */
    private AccessTokenBean accessTokenBean;

    private static final String URL = "https://api.weixin.qq.com/cgi-bin/token";

    /**
     * 获取access token
     *
     * @param appId
     * @param appSecret
     */
    private void refreshAccessToken(String appId, String appSecret) throws IOException {
        String s = HttpClientUtils.get(URL, AccessTokenBean.requestOf(appId, appSecret));
        JSONObject jsonObject = JSONObject.parseObject(s);
        long expiresIn = jsonObject.getLong("expires_in");
        String accessToken = jsonObject.getString("access_token");
        accessTokenBean = AccessTokenBean.responseOf(accessToken, expiresIn);
    }

    /**
     * 获取access token
     *
     * @return
     */
    public String getAccessToken() throws IOException {
        if (accessTokenBean == null || accessTokenBean.isExpired()) {
            refreshAccessToken(charConfig.getAppId(), charConfig.getSecret());
        }
        return accessTokenBean.getAccessToken();
    }

}